import 'dart:async';

import 'package:gold/app/recover_order_event.dart';
import 'package:gold/base/config.dart';
import 'package:gold/base/list_view_model.dart';
import 'package:gold/http/api_gold.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/gold_recover_order_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/widgets/dialog/confirm_dialog.dart';
import 'package:gold/widgets/dialog/recover_order_cancel_dialog.dart';

/// @description: 黄金回收订单列表状态
/// @author tangzhentao
/// @created at 21:34 2024/12/14

class OnlineListViewmodel extends ListViewModel<GoldRecoverOrderModel> {
  /// 黄金回收订单状态 [RecoverOrderStatus]
  final String status;

  /// 取消订单监听
  StreamSubscription<RecoverCancel>? _cancelSubscription;
  /// 自行寄快递监听
  StreamSubscription<RecoverSetExpress>? _expressSubscription;
  /// 确认交易监听
  StreamSubscription<RecoverConfirm>? _confirmSubscription;

  OnlineListViewmodel(super.api, this.status) {
    isLast = false;
    /// 取消订单
    if (status == RecoverOrderStatus.all || status == RecoverOrderStatus.canceled) {
      _cancelSubscription = XfgNav.eventBus.on<RecoverCancel>().listen((result) => refresh());
    }
    /// 自行寄快递
    if (status == RecoverOrderStatus.all || status == RecoverOrderStatus.unReceipt) {
      _expressSubscription = XfgNav.eventBus.on<RecoverSetExpress>().listen((result) => refresh());
    }
    /// 确认交易
    if (status == RecoverOrderStatus.all || status == RecoverOrderStatus.done) {
      _cancelSubscription = XfgNav.eventBus.on<RecoverCancel>().listen((result) => refresh());
    }
  }

  /// 取消订单
  Future cancelOrder(int index) async {
    if (!_isValidOrder(index)) return;
    final reason = await showRecoverCancelDialog();
    if (reason != null) {
      final order = list[index];
      final result = await Http().request<dynamic>(ApiGold.recycleCancel, successText: '已取消订单', data: {
        'id': order.id, 'reason': reason});
      if (result.success) {
        if (status == RecoverOrderStatus.unPickUp) {
          /// 当前代取件页面
          _removeAt(index);
        } else {
          XfgNav.eventBus.fire(RecoverCancel(order.id!));
        }
      }
    }
  }

  /// 自行寄快递
  Future expressDelivery(int index) async {
    if (!_isValidOrder(index)) return;
    final result = await XfgNav.pushNamed(Routes.settingsSetExpress, arguments: {'orderId': list[index].id!});
    if (result == true) {
      if (status == RecoverOrderStatus.unPickUp) {
        /// 当前待取件页面
        _removeAt(index);
      } else {
        XfgNav.eventBus.fire(RecoverSetExpress(list[index].id!));
      }
    }
  }

  /// 查看核料视频
  Future viewNuclearMaterialVideo(int index) async {
    final auditVideo = list[index].auditVideo;
    // final auditVideo = 'https://media.w3.org/2010/05/sintel/trailer.mp4';
    if (auditVideo?.isNotEmpty == true) {
      XfgNav.pushNamed(Routes.videoPlay, arguments: auditVideo);
    } else {
      '视频信息异常'.error();
    }
  }

  /// 确认交易
  Future confirmDeal(int index) async {
    final result = await showConfirmDialog(title: '确认交易', content: '确认交易之后，订单无法为您提供 售后问题，请慎重操作', cancel: '取消');
    if (result == true) {
      final confirmResult = await Http().request<dynamic>(ApiGold.recycleConfirm,
          data: {'id': list[index].id},
          loadingText: '确认中...', successText: '确认交易成功');
      if (confirmResult.success) {
        if (status == RecoverOrderStatus.unConfirm) {
          /// 当前待确认页面
          _removeAt(index);
        } else {
          XfgNav.eventBus.fire(RecoverConfirm(list[index].id!));
        }
      }
    }
  }

  /// 查看物流
  /// [index] 下标
  /// [isShipLogistics] 是否发货物流
  Future checkLogistics(int index, bool isShipLogistics) async {
    final order = list[index];
    final expressDetail = isShipLogistics ? order.express?.expressDetail:order.refund?.express?.expressDetail;
    if (expressDetail != null) {
      XfgNav.pushNamed(Routes.myOrderRecoverLogistics, arguments: {
        'isShip': isShipLogistics, 'weight': order.weight?? 0, 'express': expressDetail});
    } else {
      '物流信息异常'.info();
    }
  }

  /// 订单详情
  Future toDetailPage(int index) async {
    final order = list[index];
    if (order.id != null) {
      XfgNav.pushNamed(Routes.myOrderRecoverOnlineDetail, arguments: order);
    } else {
      '无效订单'.info();
    }
  }

  /// 移除传入下标数据并刷新
  void _removeAt(int index) {
    list.removeAt(index);
    if (list.isNotEmpty) {
      setSuccessChange();
    } else {
      setEmpty();
    }
  }

  /// 有效订单
  bool _isValidOrder(int index) {
    final id = list[index].id;
    final result = id != null;
    if (!result) {
      '订单信息异常'.error();
    }
    return result;
  }

  @override
  Map<String, dynamic>? onOtherData() {
    return {"filter": {"method": RecoverType.online, "status": status}};
  }

  @override
  void dispose() {
    _cancelSubscription?.cancel();
    _cancelSubscription = null;
    _expressSubscription?.cancel();
    _expressSubscription = null;
    _confirmSubscription?.cancel();
    _confirmSubscription = null;
    super.dispose();
  }
}
